<template>
  <view style="text-align: center; margin-top: 15vh;">
    <image
      v-if="qrCodeImage"
      :src="qrCodeImage"
      alt="QR Code"
      style="width: 80vw; height: 80vw;"
    />

    <view class="u-m-40" style="margin-top: 20vh !important;">
      <u-button
        v-if="qrCodeImage"
        :color="$u.color.mainColor"
        @click="saveQRCodeToAlbum"
      >下载二维码</u-button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { user } from '@/utils/api'

const base64DataUrl = ref(null)
const qrCodeImage = ref(null)

const saveQRCodeToAlbum = () => {
  if (!qrCodeImage.value) {
    uni.showToast('二维码尚未加载')
    return
  }

  // 将 Base64 字符串转换为临时文件
  const fs = uni.getFileSystemManager()
  const filePath = `${uni.env.USER_DATA_PATH}/qrcode.png`

  fs.writeFile({
    filePath: filePath,
    data: base64DataUrl.value,
    encoding: 'base64',
    success: () => {
      uni.authorize({
        scope: 'scope.writePhotosAlbum',
        success() {
          // 保存图片到相册
          uni.saveImageToPhotosAlbum({
            filePath: filePath,
            success: () => {
              uni.showToast({
                title: '已保存到相册'
              })
            },
            fail: (err) => {
              uni.showModal({
                title: '保存图片到相册失败',
                content: err.errMsg,
                showCancel: false
              })
              if (err.errMsg.includes('auth denied')) {
                uni.showToast('请授权保存图片到相册')
                uni.openSetting({
                  success: (settingData) => {
                    if (settingData.authSetting['scope.writePhotosAlbum']) {
                      saveQRCodeToAlbum() // 重新尝试保存
                    }
                  }
                })
                saveQRCodeToAlbum()
              } else {
                uni.showToast({
                  title: '保存到相册失败'
                })
              }
            }
          })
        }
      })
      
    },
    fail: (err) => {
      console.error('写入文件失败:', err)
      uni.showToast('写入文件失败')
    }
  })
}

onMounted(() => {
  console.log(uni.getSystemInfoSync().host)
  let func;
  if (uni.getSystemInfoSync().host && uni.getSystemInfoSync().host.env == 'WeChat') {
    func = user.wxQrCode
  } else if (uni.getSystemInfoSync().host === 'KUAISHOU') {
    func = user.ksQrCode
  }
  func({
    "width": 860,
    "pagePath": "pages/index/index",
    "isAutoColor": true,
    "isHyaline": true,
    "requireCheckPath": false
  }).then(res => {
    // 假设 res.data 包含 Base64 编码的图片字符串
    if (res.data) {
      base64DataUrl.value = res.data
      qrCodeImage.value = `data:image/png;base64,${res.data}`
    }
  }).catch(err => {
    console.error('获取二维码失败:', err)
  })
})
</script>

<style lang="scss" scoped>
/* 你的样式 */
</style>